import 'dart:async';
import 'dart:convert';

import 'package:chathouse/model/member_info.dart';
import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/pages/expert/edit_expert_service.dart';
import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:image_picker/image_picker.dart';

import '../../../constant/app_constant.dart';
import '../../../widgets/my_drop_down_widget.dart';
import '../../../widgets/my_input_widget.dart';

///編輯专家檔案
class EditExpertAccountPage extends StatefulWidget {
  const EditExpertAccountPage({Key? key}) : super(key: key);

  @override
  State<EditExpertAccountPage> createState() => _EditExpertAccountPageState();
}

class _EditExpertAccountPageState extends State<EditExpertAccountPage> with NavigationHelper {
  String? imageUrl;

  MemberInfo? _memberInfo;
  TextEditingController companyController = TextEditingController();
  TextEditingController nameController = TextEditingController();

  TextEditingController phoneTextEditingController = TextEditingController();
  TextEditingController emailTextEditingController = TextEditingController();

  String areaSelectedValue = "0";
  List<MyDropDownBean> areas = [
    MyDropDownBean("0", "+852"),
    MyDropDownBean("1", "+86"),
  ];

  late StreamSubscription<bool> keyboardSubscription;
  bool keyboardVisible = false;

  @override
  void initState() {
    super.initState();
    Object? json = SpUtil.getObject2(AppConstant.memberInfo);
    if (json != null) {
      _memberInfo = MemberInfo.fromJson2(json);
      imageUrl = _memberInfo?.data?.memberImage;
      companyController.text = _memberInfo?.data?.membersCorporation ?? "";
      nameController.text = _memberInfo?.data?.membersName ?? "";
      emailTextEditingController.text = _memberInfo?.data?.membersEmail ?? "";
      String nameText = _memberInfo?.data?.membersPhone ?? "";
      String areaText = "";
      if (nameText.startsWith("852")) {
        areaSelectedValue = "0";
        areaText = "852";
      }
      if (nameText.startsWith("86")) {
        areaSelectedValue = "1";
        areaText = "86";
      }
      var newName = nameText.replaceFirst(areaText, "");
      phoneTextEditingController.text = newName;
      setState(() {});
      // Net.getInstance().setDio("PROXY 192.168.6.140:8888");
    }

    var keyboardVisibilityController = KeyboardVisibilityController();
    // Subscribe
    keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
      keyboardVisible = visible;
      LogUtil.d("keyboardVisible:${keyboardVisible}");
    });
  }

  @override
  void dispose() {
    companyController.dispose();
    nameController.dispose();
    phoneTextEditingController.dispose();
    emailTextEditingController.dispose();
    keyboardSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var keyboardSize = MediaQuery.of(context).viewInsets.bottom;
    LogUtil.d("keyboardSize${keyboardSize}");
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: getAppBar(
          title: "編輯專家檔案",
          navigationHelperBack: () {
            back();
          }),
      body: ListView(
        children: [
          Container(
                  margin: EdgeInsets.only(top: 24.w),
                  alignment: Alignment.center,
                  child: (imageUrl?.isNullOrEmpty ?? true)
                      ? ImageUtils.image(Res.expert_avatar, width: 80.w, height: 80.w, radius: 40.w).setContainer(margin: EdgeInsets.only(right: Styles.magin_24))
                      : ImageUtils.image(imageUrl ?? "", imageType: ImageType.NETWORK, fit: BoxFit.cover, width: 80.w, height: 80.w, radius: 40.w).setContainer(margin: EdgeInsets.only(right: Styles.magin_24)))
              .setOnClickListener(() {
            onAddImage();
          }),
          MyInputWidget(
            title: "聯絡人/公司名稱*",
            textStyle: getTextStyle(18.sp, fontType: FontType.MID),
            controller: companyController,
          ).setContainer(margin: EdgeInsets.only(top: 12.w)),
          MyInputWidget(
            title: "暱稱*",
            textStyle: getTextStyle(18.sp, fontType: FontType.MID),
            controller: nameController,
          ).setContainer(margin: EdgeInsets.only(top: 12.w)),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "電話號碼*",
                style: getTextStyle(18.sp, color: Colors.black, fontType: FontType.MID),
              ).setContainer(margin: EdgeInsets.only(bottom: 4.w)),
              Row(
                children: [
                  MyDropDownWidget(areaSelectedValue, areas, (val) {
                    areaSelectedValue = val;
                    setState(() {
                      LogUtil.d("更新了 $areaSelectedValue");
                      phoneTextEditingController.clear();
                    });
                  }).setContainer(width: 100.w),
                  Expanded(
                      child: MyInputWidget(
                    placeholder: "電話號碼",
                    controller: phoneTextEditingController,
                    keyboardType: TextInputType.number,
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                      LengthLimitingTextInputFormatter(areaSelectedValue == "0" ? 8 : 11), // 限制长度为8位
                    ],
                  ).setContainer(margin: EdgeInsets.only(left: 6.w)))
                ],
              ),
            ],
          ).setContainer(margin: EdgeInsets.only(top: 20.w)),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "電郵*",
                style: getTextStyle(18.sp, color: Colors.black, fontType: FontType.MID),
              ).setContainer(margin: EdgeInsets.only(bottom: 4.w)),
              MyInputWidget(
                leftIcon: Icon(
                  Icons.email_outlined,
                  size: 24.w,
                  color: MyColors.gary_155155155,
                ).setContainer(margin: EdgeInsets.only(right: 4.w)),
                placeholder: "電郵",
                controller: emailTextEditingController,
              ),
            ],
          ).setContainer(margin: EdgeInsets.only(top: 20.w)),
          Text(
            "* 必須填寫",
            style: getTextStyle(18.sp, color: Colors.black, fontType: FontType.DEFAULT),
          ).setContainer(margin: EdgeInsets.only(top: 12.w)),
          SizedBox(
            height: 60.w,
          ),
          Row(
            //必须加Row 不加 会铺满宽度  无法指定宽度
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("下一頁", style: getTextStyle(20.sp, color: Colors.white))
                  .setContainer(
                height: 50.w,
                width: 150.w,
                decoration: BoxDecoration(color: Styles.mainColor, borderRadius: BorderRadius.circular(25.w)),
                alignment: Alignment.center,
              )
                  .setOnClickListener(() {
                if (companyController.text.isEmpty) {
                  ToastUtil.showToast("請輸入聯絡人/公司名稱");
                  return;
                }
                if (nameController.text.isEmpty) {
                  ToastUtil.showToast("請輸入暱稱");
                  return;
                }
                if (areaSelectedValue == "0") {
                  if (phoneTextEditingController.text.length != 8) {
                    ToastUtil.showToast("輸入的電話號碼不合法");
                    return;
                  }
                } else if (areaSelectedValue == "1") {
                  if (phoneTextEditingController.text.length != 11) {
                    ToastUtil.showToast("輸入的電話號碼不合法");
                    return;
                  }
                }
                if (emailTextEditingController.text.isEmpty) {
                  ToastUtil.showToast("請輸入電郵");
                  return;
                }
                String area = areas
                    .firstWhere((element) {
                      return areaSelectedValue == element.value;
                    })
                    .name
                    .substring(1);
                String membersPhone = phoneTextEditingController.text.isNotEmpty ? (area + phoneTextEditingController.text) : "";
                var map = {
                  "company": companyController.text,
                  "name": nameController.text,
                  "phone": membersPhone,
                  "email": emailTextEditingController.text,
                  "imageUrl": imageUrl,
                };
                Get.to(EditExpertService(map));
                // onSave();
              }, isInkWell: true),
            ],
          ),
          SizedBox(
            height: keyboardVisible ? keyboardSize : 20.w,
          ),
        ],
      ).setContainer(padding: EdgeInsets.symmetric(horizontal: 32.w)),
    );
  }

  onAddImage() async {
    int type = await Get.bottomSheet(Container(
      width: 1.sw,
      height: 120.w,
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w))),
      child: Column(
        children: [
          Text(
            "從相冊中選取",
            style: getTextStyle(18.sp, color: Colors.black),
          ).setContainer(width: double.infinity, height: 60.w, alignment: Alignment.center, decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1.0.w, color: MyColors.gary_149149149)))).setOnClickListener(() {
            Get.back(result: 1);
          }),
          Expanded(
              child: Text(
            "取消",
            style: getTextStyle(18.sp, color: Colors.black),
          ).setContainer(alignment: Alignment.center).setOnClickListener(() {
            Get.back();
          })),
        ],
      ),
    ));
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: type == 1 ? ImageSource.gallery : ImageSource.camera);
    var imgData = await image?.readAsBytes();
    if (imgData == null) {
      return;
    }
    if (imgData.isEmpty) {
      return;
    }
    Obj.showLoading();
    Map result;
    String? url;
    Apis.uploadFile(imgData, image?.name ?? "image.png")
        .then((response) => {
              Obj.dismissLoading(),
              debugPrint("upload=${response?.data.toString()}"),
              result = jsonDecode(response?.data ?? ""),
              url = result["url"],
              if (url != null)
                {
                  LogUtil.d(imageUrl),
                  setState(() {
                    imageUrl = url!;
                  }),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }
}
